<template>
  <n-space
    vertical
    size="large"
  >
    <n-layout-header bordered>
      <n-space justify="space-between">
        <n-gradient-text
          type="info"
          :size="24"
        >
          阶段栏：{{ fieldTree.getFieldDataById(surfaceSetting.getShowField())?.topic }}
        </n-gradient-text>
        <n-space>
          <template
            v-for="(data, index) in showCountTag"
            :key="index"
          >
            <n-tag type="success"> {{ data.name }}：{{ data.count }} </n-tag>
          </template>
        </n-space>
        <n-button
          @click="addNewOne()"
          type="primary"
          dashed
          >添加新阶段</n-button
        >
      </n-space>
    </n-layout-header>
    <n-layout
      has-sider
      style="height: 320px"
    >
      <n-layout-sider
        bordered
        show-trigger
        collapse-mode="width"
        :collapsed-width="64"
        :width="150"
        :native-scrollbar="false"
        style="max-height: 320px"
      >
        <n-menu
          v-model:value="StageState"
          :collapsed-width="64"
          :collapsed-icon-size="22"
          :options="satgeMenuOptions"
        />
      </n-layout-sider>
      <n-layout-content content-style="padding: 24px;">
        <n-data-table
          v-show="!showEmpty"
          :columns="columns"
          :data="tableData"
          :pagination="false"
          :bordered="false"
          id="stageDragTable"
          :row-props="rowProps"
        />
        <n-data-table
          v-show="showEmpty"
          :columns="columns"
          :data="[]"
          id="stageDragTable"
          :pagination="false"
          :bordered="false"
        />
      </n-layout-content>
    </n-layout>
    <n-dropdown
      placement="bottom-start"
      trigger="manual"
      :x="xRef"
      :y="yRef"
      :options="options"
      :show="showDropdownRef"
      :on-clickoutside="onClickoutside"
      @select="handleSelect"
    />
  </n-space>
  <StageEditDrawer v-model="editSettings"></StageEditDrawer>
  <StageDelModal v-model="editSettings"></StageDelModal>
</template>

<script lang="ts" setup>
import StageEditDrawer from "./stageBtn/StageEditDrawer.vue";
import StageDelModal from "@/components/field/stages/stageBtn/StageDelModal.vue";
import { RemoveMethods } from "@/types/remove-methods";
import { StateMoal } from "@model/StateMoal";
import { StageList, TaskIdsModal, TimeLogModel } from "@model/stage";
import { SurfaceSetting } from "@model/surfaceSetting";
import UseCacheFinishStageMap from "@pinias/UseCacheFinishStageMap";
import UseFieldTree from "@pinias/UseFieldTree";
import UseStage from "@pinias/UseStage";
import UseSurfaceSetting from "@pinias/UseSurfaceSetting";
import pinia from "@pinias/pinia";
import { renderIcon } from "@utils/CommonUtils";
import * as DateUtils from "@utils/DateUtils";
import { Book } from "@vicons/ionicons5";
import { NButton, NDataTable, NSpace, NLayout, NLayoutSider, NLayoutContent, NLayoutHeader, NMenu } from "naive-ui";
import Sortable from "sortablejs";
import { h, ref, onMounted, watch, reactive } from "vue";

// 全局数据
const { getSurfaceSetting } = UseSurfaceSetting(pinia);
const surfaceSetting: SurfaceSetting = getSurfaceSetting();
const { getStageList } = UseStage(pinia);
const stageList: StageList = getStageList();
const { getFieldTree } = UseFieldTree(pinia);
const fieldTree = getFieldTree();
const { getCacheFinishStageMap } = UseCacheFinishStageMap(pinia);
const cacheFinishStageMap = getCacheFinishStageMap();

// 当前页面数据
const showEmpty = ref(true);
const StageState = ref(surfaceSetting.StageState);
const satgeMenuOptions = ref(
  StateMoal.getStateMap().map(value => {
    value.icon = renderIcon(Book);
    return value;
  }),
);
const editSettings = reactive<{ toEdit: boolean; toDelete: boolean; toDealRowId: number | undefined }>({
  toEdit: false,
  toDelete: false,
  toDealRowId: undefined,
});
const showCountTag = ref(new Array<{ name: string; count: number }>());
class RowData {
  id: number;
  name: string;
  takeTime: string;
  lastStartTime: string;
  lastEndTime: string;
  startTime: Array<TimeLogModel>;
  finishRatio: number;

  constructor(data: RemoveMethods<RowData>) {
    Object.assign(this, data);
  }
  static getNullModel() {
    return new RowData({
      id: -1,
      name: "",
      takeTime: "",
      lastEndTime: "",
      lastStartTime: "",
      startTime: [],
      finishRatio: 0,
    });
  }
}

// 表格数据
const getTableData = async () => {
  const result = [];
  const showField = surfaceSetting.getShowField();
  const fieldData = fieldTree.getFieldDataById(showField);
  showCountTag.value = StateMoal.getStateCount(fieldData?.stageIds);
  const finishStageList = await cacheFinishStageMap.getFinishStageList(showField);
  showCountTag.value[2].count = finishStageList.finishStageList.length;
  if (fieldData !== undefined) {
    if (surfaceSetting.StageState === "finished") {
      if (showField !== undefined) {
        const list = finishStageList.finishStageList;
        for (let i = 0; i < list.length; i++) {
          const oldDdata = list[i];
          if (oldDdata !== undefined) {
            const lastTime = TimeLogModel.getLastStartEndTime(
              oldDdata.startTime,
              oldDdata.lastStartTime,
              surfaceSetting.StageState,
            );
            // console.log((task["1"]["已完成"].length+task["2"]["已完成"].length))
            result.push(
              new RowData({
                id: oldDdata.id,
                name: oldDdata.name,
                takeTime: TimeLogModel.computeTakeTime(oldDdata.startTime),
                lastEndTime: DateUtils.timestampToDateTime(lastTime.endTime),
                lastStartTime: DateUtils.timestampToDateTime(lastTime.startTime),
                startTime: oldDdata.startTime,
                finishRatio: 100,
              }),
            );
          }
        }
      }
    } else {
      const list = StateMoal.getStateId(fieldData.stageIds, surfaceSetting.StageState);
      // console.log(list);
      for (var i = 0; i < list.length; i++) {
        const id = list[i];
        const oldDdata = stageList.getStageDataById(id);
        if (oldDdata !== undefined) {
          const task = oldDdata.task;
          // console.log((task["1"]["已完成"].length+task["2"]["已完成"].length))
          const lastTime = TimeLogModel.getLastStartEndTime(
            oldDdata.startTime,
            oldDdata.lastStartTime,
            surfaceSetting.StageState,
          );
          result.push(
            new RowData({
              id: oldDdata.id,
              name: oldDdata.name,
              takeTime: TimeLogModel.computeTakeTime(oldDdata.startTime),
              lastEndTime: DateUtils.timestampToDateTime(lastTime.endTime),
              lastStartTime: DateUtils.timestampToDateTime(lastTime.startTime),
              startTime: oldDdata.startTime,
              finishRatio: TaskIdsModal.computeFinishRation(task),
            }),
          );
        }
      }
    }
  }
  if (result.length == 0) {
    result.push(RowData.getNullModel());
    showEmpty.value = true;
  } else showEmpty.value = false;
  return result;
};
const tableData = ref(new Array<RowData>());
const watchTableData = async () => {
  tableData.value = await getTableData();
  // console.log(tableData.value)
};
watch(() => {
  surfaceSetting.StageState = StageState.value;
  return StageState.value;
}, watchTableData);
watch(stageList, watchTableData);
watch(surfaceSetting.showField, watchTableData);
// 渲染表头
const play = (row: RowData) => {
  // message.info(`Play ${row.title}`);
  console.log(row);
};
const createColumns = () => {
  return [
    // {
    //   title: "id",
    //   key: "id",
    // },
    {
      title: "名字",
      key: "name",
    },
    {
      title: "所花时间",
      key: "takeTime",
    },
    {
      title: "上次开始时间",
      key: "lastStartTime",
    },
    {
      title: "上次结束时间",
      key: "lastEndTime",
    },
    {
      title: "完成率(%)",
      key: "finishRatio",
    },
    {
      title: "Action",
      key: "actions",
      render(row: RowData) {
        return h(
          NButton,
          {
            strong: true,
            tertiary: true,
            size: "small",
            id: "handle-drag",
            onClick: () => play(row),
          },
          { default: () => "Play" },
        );
      },
    },
  ];
};
const columns = createColumns();

// 右键菜单
const rowProps = (row: RowData) => {
  return {
    onContextmenu: (e: MouseEvent) => {
      // message.info(JSON.stringify(row, null, 2));
      showDropdownRef.value = true;
      xRef.value = e.clientX;
      yRef.value = e.clientY;
      // console.log('rowProps',row)
      editSettings.toDealRowId = row.id;
    },
  };
};
const options = [
  {
    label: "编辑",
    key: "edit",
  },
  {
    label: "查看任务",
    key: "show",
  },
  {
    label: () => h("span", { style: { color: "red" } }, "删除"),
    key: "delete",
  },
];
const showDropdownRef = ref(false);
const xRef = ref(0);
const yRef = ref(0);
const onClickoutside = () => {
  showDropdownRef.value = false;
};
const handleSelect = (key: string, node: string) => {
  console.log(key, node);
  showDropdownRef.value = false;
  if (key == "edit") {
    editSettings.toEdit = true;
  }
  if (key == "delete") {
    editSettings.toDelete = true;
  }
  if (key === "show") {
    surfaceSetting.showStage.pop();
    surfaceSetting.showStage.push(editSettings.toDealRowId);
  }
};
const addNewOne = () => {
  editSettings.toDealRowId = undefined;
  editSettings.toEdit = true;
};

// 拖拽逻辑
function setSort() {
  let el = document.querySelector("#stageDragTable table tbody");
  // console.log(el)
  // while (el === null) el = document.querySelector("#stageDragTable table tbody");
  // console.log(el)
  new Sortable(el, {
    handle: "#handle-drag",
    sort: true,
    ghostClass: "sortable-ghost",
    onEnd: (e: any) => {
      const showField = surfaceSetting.showField[0];
      const fieldData = fieldTree.getFieldDataById(showField);
      if (surfaceSetting.StageState === "finished") {
        const showField = surfaceSetting.showField[0];
        if (showField !== undefined) {
          cacheFinishStageMap.getFinishStageList(showField).then(finishStageList => {
            const list = finishStageList.finishStageList;
            const targetRow = list.splice(e.oldIndex, 1)[0];
            list.splice(e.newIndex, 0, targetRow);
            cacheFinishStageMap.changeKeys.push(showField.toString());
          });
        }
      }
      if (fieldData !== undefined && surfaceSetting.StageState !== "finished") {
        const list = StateMoal.getStateId(fieldData.stageIds, surfaceSetting.StageState);
        // console.log(list)
        const targetRow = list.splice(e.oldIndex, 1)[0];
        list.splice(e.newIndex, 0, targetRow);
        // console.log(list)
      }
      // console.log(tableData)
    },
  });
}
onMounted(async () => {
  await watchTableData();
  setSort();
});
</script>
